'use strict';

exports.main = async (event, context) => {
  console.log('=== markMessageRead 云函数开始 ===')
  console.log('1. 接收参数:', event)
  
  const db = uniCloud.database();
  const { messageId, userId } = event;

  if (!messageId || !userId) {
    console.log('❌ 缺少必要参数:', { messageId, userId })
    return {
      code: 400,
      msg: '缺少必要参数'
    };
  }

  try {
    console.log('2. 标记消息为已读...')
    
    // 先检查消息是否存在且属于当前用户
    const messageRes = await db.collection('interaction-messages')
      .doc(messageId)
      .get();
    
    if (!messageRes.data || messageRes.data.length === 0) {
      console.log('❌ 消息不存在:', messageId)
      return {
        code: 404,
        msg: '消息不存在'
      };
    }
    
    const message = messageRes.data[0];
    if (message.receiver_id !== userId) {
      console.log('❌ 无权操作此消息:', { messageReceiver: message.receiver_id, currentUser: userId })
      return {
        code: 403,
        msg: '无权操作此消息'
      };
    }
    
    // 更新消息为已读状态
    const result = await db.collection('interaction-messages')
      .doc(messageId)
      .update({
        is_read: true
      });
    
    console.log('3. 更新结果:', result)
    console.log('✅ 消息标记为已读成功')

    return {
      code: 200,
      msg: '消息已标记为已读',
      data: result
    };
  } catch (error) {
    console.error('❌ 标记消息失败:', error);
    return {
      code: 500,
      msg: '标记消息失败',
      error: error.message
    };
  }
};
